package com.example.javabeantotypescript.script;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;

/**
 * 描述：
 * 读取文件
 *
 * @author 12859
 * @date 2018/12/26-18:04
 */
public class ReadData {

  public void readData(String filePath, String pathTs) {
    File file = new File(filePath);
    File fileTypescript = new File(pathTs + "/CommonData.ts");
    File tableData = new File(pathTs + "/TableData.ts");
    try (OutputStream outputStream = new FileOutputStream(fileTypescript); OutputStream outputStreamTable = new FileOutputStream(tableData)) {
      StringBuilder tsBuffer = new StringBuilder();
      StringBuilder tableBuffer = new StringBuilder();
      if (file.isDirectory()) {
        File[] filesList = file.listFiles();
        for (File file1 : filesList) {
          Class classSun = Class.forName("com.example.javabeantotypescript.entity." + file1.getName().split("\\.")[0]);
          ApiModel apiModel = (ApiModel) classSun.getAnnotation(ApiModel.class);
          tsBuffer.append("/**\n" +
                  " * " + apiModel.description() + "\n" +
                  " */\n" +
                  "export interface " + classSun.getSimpleName() + "{\n");
          tableBuffer.append("export const " + classSun.getSimpleName() + " = [\n");
          for (Field declaredField : classSun.getDeclaredFields()) {
            String type = declaredField.getType().equals(Integer.class) ? "number" : "string";
            String annationValue = "  ";
            if (declaredField.getAnnotation(ApiModelProperty.class) != null) {
              annationValue = declaredField.getAnnotation(ApiModelProperty.class).value();
            }
            tsBuffer.append("  /** " + annationValue + " */\n" +
                    "  " + declaredField.getName() + "?: " + type + ";\n");
            tableBuffer.append("{\n" +
                    "      title: \"" + annationValue + "\",\n" +
                    "      align: \"center\",\n" +
                    "      dataIndex: \"" + declaredField.getName() + "\",\n" +
                    "      key: \"" + declaredField.getName() + "\",\n" +
                    "    },");
          }
          tsBuffer.append("}\n");
          tableBuffer.append("];\n");
        }
      } else {

      }
      outputStream.write(tsBuffer.toString().getBytes());
      outputStreamTable.write(tableBuffer.toString().getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }

  public void readFile(String filePath, String pathTs) {

  }
}
